package com.d2.modules.system.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.d2.modules.system.permission.entity.Resource;
import com.d2.modules.system.permission.mapper.IResourceMapper;
import com.d2.modules.system.permission.service.IResourceService;
import com.d2.modules.system.permission.service.IRoleResourceService;
import com.d2.modules.system.permission.service.IRoleService;
import com.d2.modules.system.permission.util.UserContext;
import com.d2.modules.system.permission.util.filter.DataScope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class ResourceServiceImpl extends ServiceImpl<IResourceMapper, Resource> implements IResourceService {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IRoleResourceService roleResourceService;

    @Override
    public List<Resource> permissionTree() {
        List<Long> permissions = roleResourceService.queryResourceByUserId(UserContext.get().getId());
        Resource q = new Resource();
        q.setPid(0L);
        QueryWrapper<Resource> queryWrapper = new QueryWrapper<>(q);
        if (!permissions.isEmpty()) {
            queryWrapper.in("id", permissions);
        } else {
            return Collections.emptyList();
        }
        List<Resource> list = this.list(queryWrapper);
        buildTree(permissions, list, null);
        return list;
    }

    @Override
    public List<Resource> tree(Long exclude) {
        Resource q = new Resource();
        q.setPid(0L);
        LambdaQueryWrapper<Resource> queryWrapper = Wrappers.lambdaQuery(q);
        queryWrapper.notIn(exclude != null,Resource::getId, exclude);
        List<Resource> list = this.list(queryWrapper);
        buildTree(null, list, exclude);
        return list;
    }

    @Override
    public List<Resource> tree() {
       return this.tree(null);
    }

    private void buildTree(List<Long> permissions, List<Resource> list, Long exclude) {
        for (Resource m : list) {
            Resource query = new Resource();
            query.setPid(m.getId());
            LambdaQueryWrapper<Resource> qw = Wrappers.lambdaQuery(query);
            qw.in(permissions != null,Resource::getId, permissions);

                qw.notIn(exclude != null,Resource::getId, exclude);
            List<Resource> list1 = this.list(qw);
            this.buildTree(permissions, list1, exclude);
            m.setChildren(list1);
        }
    }
}
